package com.holystone.splunk.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (c) 2017, HOLYSTONE Technologies, Inc.
 * All right reserved.
 *
 * @author huyan
 * @date 2017/11/6
 * @desc:
 */
public class StringUtils {

    private static final String DEFAULT_ENCODE = "utf-8";

    /**
     * 将输入流按照utf格式转成字符串
     * @param is
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream is) throws IOException {
        return inputStream2String(is, DEFAULT_ENCODE);
    }


    /**
     * 将输入流按照指定编码格式转成字符串
     * @param inputStream
     * @param encode
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream inputStream, String encode) throws IOException {
        StringBuffer str = new StringBuffer();
        if (encode == null || encode == "") {
            encode = DEFAULT_ENCODE;
        }
//        BufferedReader br = new BufferedReader(new InputStreamReader(is, encode));
//        StringBuilder sb = new StringBuilder();
//        while ((str = br.readLine()) != null) {
//            sb.append(str).append("\n");
//        }
//        return sb.toString();

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        inputStream.close();
        str.append(result.toString(encode));
        return str.toString();
    }



    /**
     * 将list数组转换为以 "," 分割的字符串
     * @param list
     * @return
     */
    public static String List2Str(List<? extends Object> list) {
        if (list == null || list.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Object obj : list) {
            sb.append(obj).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 将数组转为集合
     * @param tArr
     * @param <T>
     * @return
     */
    public static <T> List<T> array2List(T[] tArr) {
        List<T> list = new ArrayList<>();
        for (T t : tArr) {
            if (t != null)
                list.add(t);
        }
        return list;
    }

    public static List<String> str2List(String string) {
        if (string == null || "".equals(string))
            return null;
        List<String> strList = new ArrayList<>();
        for (String str : string.split(",")) {
            strList.add(str.trim());
        }
        return strList;
    }
}
